package com.arong.biBackend.service.impl;

import com.arong.biBackend.model.dto.db.DbInsertDataDto;
import com.arong.biBackend.model.dto.db.DbNewDto;
import com.arong.biBackend.model.entity.Chart;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.arong.biBackend.service.ChartService;
import com.arong.biBackend.mapper.ChartMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class ChartServiceImpl extends ServiceImpl<ChartMapper, Chart>
    implements ChartService{

    @Resource
    ChartMapper chartMapper;

    /**
     * 根据数据生成新表
     * @param tableName 表名称
     * @param data 数据
     */
    @Override
    public void genTableByCSVData(String tableName, String data) {
            // 提取列名和数据
            String[] lines = data.split("\n");
            String[] headers = lines[0].split(",");
            String[] types = lines[1].split(",");

            // 创建colMap
            Map<String, String> colMap = new HashMap<>();

            // 主键为什么会在最后一列出现呢
            if(!headers[0].equals("id")) {
                // 默认添加主键
                colMap.put("id", "bigint auto_increment primary key");
            }

            for (int i = 0; i < headers.length; i++) {
                String header = headers[i];
                String s = types[i];
                if(s == null || "字符串".equals(s)) {
                    // 输入类型为字符串的时候
                    colMap.put(header, "varchar(256)");
                } else if("数字".equals(s)) {
                    // 输入类型为数字的时候
                    colMap.put(header, "bigint(20)");
                } else {
                    // 乱七八糟默认为字符串
                    colMap.put(header, "varchar(256)");
                }
            }

            DbNewDto dbNewDto = new DbNewDto();
            dbNewDto.setTableName(tableName);
            dbNewDto.setColMap(colMap);

            chartMapper.createNewTable(dbNewDto);

            // 创建valueMapList
            List<Map<String, Object>> valueMapList = new ArrayList<>();
            for (int i = 2; i < lines.length; i++) {
                String[] values = lines[i].split(",");
                Map<String, Object> valueMap = new HashMap<>();
                for (int j = 0; j < headers.length; j++) {
                    valueMap.put(headers[j], values[j]);
                }
                valueMapList.add(valueMap);
            }

            DbInsertDataDto dto = new DbInsertDataDto();
            dto.setTableName(tableName);
            dto.setValueMapList(valueMapList);

            chartMapper.insertData(dto);
    }
}




